<template>
  <div class="app-container">
    <div class="mb10">
      <form-selections :is-active="isActive" :items="formItems" :query-param.sync="searchParams" display="block" @handleSearch="handleSearch">
        <div>
          <el-button size="mini" type="primary" class="filter-item search" icon="el-icon-search" @click="handleSearch">
            搜索
          </el-button>
          <el-button size="mini" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
        </div>
      </form-selections>
    </div>

    <div v-loading="loading" class="page-grid">
      <div class="action-group">
        <el-button v-action="'purchaseOrder@save'" size="small" type="success" icon="el-icon-circle-plus-outline" @click="addPurchaseClick">新增申请单</el-button>
        <el-button v-action="'purchaseOrder@SubmitAudit'" size="small" type="primary" @click="submitReview">提交审核</el-button>
        <el-button v-action="'purchaseOrder@changeAuditStatus'" size="small" type="primary" @click="bulkShipment(2, -1)">采购员审核</el-button>
        <el-button v-action="'purchaseOrder@operateChangeAuditStatus'" size="small" type="primary" @click="bulkShipment(3, -2)">运营审核</el-button>
        <el-button v-action="'purchaseContract@save'" size="small" type="primary" @click="transferPurchase">转为采购合同</el-button>
        <el-button v-action="'purchaseOrder@batchDelete'" size="small" type="danger" @click="batchDeleteData()">批量删除</el-button>
        <el-button v-action="'purchaseOrder@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
      </div>
      <egrid class="egrid" :screen-heigh="screenHeigh" stripe fit border highlight-current-row element-loading-text="正在努力加载中..." :column-type="['selection']" :data="tableData" :columns="columns" :columns-schema="columnsSchema" :columns-handler="columnsHandler" @selection-change="checkIds" />
      <epagination v-if="tableData" :total="total" :current="searchParams.page" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" />
    </div>
    <!-- 新增供应商 -->
    <el-dialog v-if="dialogAddVisible" v-loading.lock="loading" :title="title" :visible.sync="dialogAddVisible" :close-on-click-modal="false" width="70%" class="dialogText header-none" :element-loading-text="loadingText" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" center>
      <el-form v-if="dialogAddVisible" ref="form" v-loading="infoLoading" :model="form" :rules="roleCodeRule" label-width="auto">
        <el-row>
          <mainTilte title="基本信息" />
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购申请单编码">
              <el-input v-model.trim="form.code" disabled />
            </el-form-item>
          </el-col>
          <el-col v-if="[2, -1].includes(form.audit_status)" :span="8">
            <el-form-item label="采购总金额">
              <el-input v-model.trim="form.amount" disabled />
              <!-- <app-price :price="form.amount" /> -->
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注说明">
              <el-input v-model="form.notes" type="textarea" disabled autosize />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <mainTilte title="商品信息" />
        </el-row>
        <el-table v-if="form.products" :data="form.products" stripe fit border class="mb24">
          <el-table-column prop="goods_code" label="系统sku" width="180" align="center" />
          <el-table-column prop="goods_name" label="中文名称" width="180" align="center" />
          <el-table-column label="采购数量" prop="number" width="210" align="center">
            <template slot-scope="scope">
              <span v-if="isInfo">{{ scope.row.old_number }}</span>
              <el-form-item v-else :prop="`products[${scope.$index}].number`" :rules="numberRule" class="no-label mt22">
                <el-input-number v-model="scope.row.number" :precision="0" :min="1" @change="changeMoney(this)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="[2, -1].includes(form.audit_status)" prop="price" label="采购单价" width="210" align="center">
            <template slot-scope="scope">
              <span v-if="isInfo">{{ scope.row.price }}</span>
              <el-form-item v-else :prop="`products[${scope.$index}].price`" :rules="priceRule" class="no-label mt22">
                <el-input-number v-model="scope.row.price" :precision="2" :min="0" @change="changeMoney(this)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="[2, -1].includes(form.audit_status)" prop="price" label="采购金额" width="180" align="center">
            <template slot-scope="scope">
              <app-price :price="$computed.accMul(scope.row.price, scope.row.number)" />
            </template>
          </el-table-column>
          <el-table-column v-if="[2, -1].includes(form.audit_status)" label="需求时间" width="180" align="center">
            <template slot-scope="scope">
              {{ scope.row.delivery_date | formatDate('{y}-{m}') }}
            </template>
          </el-table-column>
          <el-table-column prop="arrive_date" label="交货日期" width="250" align="center">
            <template slot-scope="scope">
              <span v-if="isInfo">{{ scope.row.arrive_date | formatDate('{y}-{m}-{d}') }}</span>
              <el-form-item v-else :prop="`products[${scope.$index}].arrive_date`" :rules="arriveDateRule" class="no-label mt22">
                <el-date-picker v-model="scope.row.arrive_date" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="notes" label="备注" width="180" align="center" />
          <el-table-column prop="goods_name_en" label="英文名称" width="180" align="center" />
          <el-table-column v-if="[2, -1].includes(form.audit_status)" prop="supply" label="供应商" width="180" align="center" />
          <el-table-column prop="container_rate" label="箱率" width="180" align="center" />
        </el-table>
        <el-row>
          <mainTilte title="配件信息" />
        </el-row>
        <el-table v-if="form.products" :data="form.parts" stripe fit border class="mb24">
          <el-table-column prop="goods_code" label="配件编码" width="180" align="center" />
          <el-table-column prop="goods_name" label="配件名称" width="180" align="center" />
          <el-table-column label="采购数量" prop="number" width="210" align="center">
            <template slot-scope="scope">
              <span v-if="isInfo">{{ scope.row.number }}</span>
              <el-form-item v-else :prop="`parts[${scope.$index}].number`" :rules="numberRule" class="no-label mt22">
                <el-input-number v-model="scope.row.number" :precision="0" :min="1" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="delivery_date" label="交货日期" width="250" align="center">
            <template slot-scope="scope">
              <span v-if="isInfo">{{ scope.row.arrive_date | formatDate('{y}-{m}-{d}') }}</span>
              <el-form-item v-else :prop="`parts[${scope.$index}].arrive_date`" :rules="arriveDateRule" class="no-label mt22">
                <el-date-picker v-model="scope.row.arrive_date" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="notes" label="备注" min-width="180" align="center" />
          <el-table-column prop="container_rate" label="箱率" width="180" align="center" />
        </el-table>
        <div v-if="!isInfo">
          <el-row>
            <mainTilte title="审核意见" />
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="audit_status">
                <el-radio-group v-model="form.audit_status">
                  <el-radio :label="sdioAdopt">通过</el-radio>
                  <el-radio :label="sdioRadio">驳回</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col v-if="form.audit_status === -2 || form.audit_status === -1" :span="16">
              <el-form-item label="驳回原因" prop="audit_notes">
                <el-input v-model="form.audit_notes" type="textarea" autosize />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <span v-if="!isInfo" slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取消审核</el-button>
        <el-button type="primary" @click="saveData()">确认审核</el-button>
      </span>
      <span v-else slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogAddVisible = false">返回</el-button>
      </span>
    </el-dialog>
    <!-- 采购合同 -->
    <CoverContractDialog ref="coverContract" @submit="query" />
    <!--下载字段选择-->
    <DownModul :url="exportUrl" :search-param="downLoadParams" :form-visible-down.sync="formVisibleDown" titel="导出字段选择" :options-modul="optionsModul" />
  </div>
</template>

<script>
import list from '@/layout/mixin/list'
import operationBtnGroup from '@/components/base/operationBtnGroup'
import { action } from '@/directive/permission/index.js' // 权限判断指令
import dicValues from '@/components/dicTransform/index'
import codeItem from '@/components/base/code'
import appText from '@/components/appText/index'
import appHtml from '@/components/appHtml/index'
// import { downloadxlsx } from '@/utils/index'
import CoverContractDialog from './components/coverContractDialog'
import cacheList from '@/layout/mixin/cacheList'
import DownModul from '@/components/DownModul/index.vue'
import { formatDate } from '@/filters/index.js'
import { accMul } from '@/utils/index'
export default {
  name: 'PurchaseRequisition',
  directives: {
    action
  },
  components: {
    CoverContractDialog,
    DownModul
    // appHtml
  },
  mixins: [list, cacheList],
  data() {
    const DICTIONARIES = {
      auditStatus: [
        // 审核状态 0-待提交 1-待采购员审核 2-待运营审核 3-运营审核通过     -1 采购员审核驳回 -2 运营员审核驳回
        {
          code: 0,
          name: '待提交'
        },
        {
          code: 1,
          name: '待采购员审核'
        },
        {
          code: 2,
          name: '待运营审核'
        },
        {
          code: 3,
          name: '运营审核通过'
        },
        {
          code: -1,
          name: '采购员审核驳回'
        },
        {
          code: -2,
          name: '运营员审核驳回'
        }
      ],
      // 是否生成合同  0-未生成 1-已生成
      cooperationStatus: [
        { code: 0, name: '未生成' },
        { code: 1, name: '已生成' }
      ]
    }
    const codeClickHandler = (code) => {
      const item = this.tableData.find((e) => e.code === code)
      this.dialogAddVisible = true
      this.isInfo = true
      this.getSupplierList(item.id)
    }
    return {
      screenHeigh: document.body.clientHeight - 365,
      componentName: 'PurchaseRequisition',
      value: '',
      value1: [],
      loading: false,
      dialogAddVisible: false, // 新增供应商弹框
      isInfo: false,
      title: '',
      loadingText: '',
      rule: {},
      /** *
       * 定义搜索框
       */
      searchParams: {
        page: 1,
        limit: 10, // 默认是10
        totalRows: 0,
        pageSizeX: [10, 20, 30, 40, 50, 100], // 每页显示个数选择器的选项设置
        value: '',
        type: '',
        audit_status: '',
        contract_code: '',
        code: '',
        start_at_creat: '',
        end_at_creat: ''
      },
      isActive: false,
      formItems: [
        {
          label: '采购单编码',
          key: 'code',
          type: 'input',
          placeholder: '请输入采购单编码'
        },
        {
          label: '合同编码',
          key: 'contract_code',
          type: 'input',
          placeholder: '请输入合同编码'
        },
        {
          label: '审核状态',
          key: 'audit_status',
          type: 'select',
          filterable: true,
          placeholder: '请选择审核状态',
          options: [
            {
              value: 0,
              label: '待提交'
            },
            {
              value: 1,
              label: '待采购员审核'
            },
            {
              value: 2,
              label: '待运营审核'
            },
            {
              value: 3,
              label: '运营审核通过'
            },
            {
              value: -1,
              label: '采购员审核驳回'
            },
            {
              value: -2,
              label: '运营员审核驳回'
            }
          ]
        },
        {
          label: '日期',
          key: 'dateCreat',
          type: '',
          valueFormat: 'yyyy-MM-dd HH:mm:ss',
          placeholder: '请选择时间范围'
          //   wrap: true
        }
      ],
      statusList: [
        {
          code: 0,
          name: '待提交'
        },
        {
          code: 1,
          name: '待采购员审核'
        },
        {
          code: 2,
          name: '待运营审核'
        },
        {
          code: 3,
          name: '运营审核通过'
        },
        {
          code: -1,
          name: '采购员审核驳回'
        },
        {
          code: -2,
          name: '运营员审核驳回'
        }
      ],
      /** *
       * 定义显示的表格
       */
      columns: [
        {
          label: '采购申请单编码',
          prop: 'code',
          width: '200',
          align: 'center',
          tooltip: false
        },
        // {
        //   label: '采购总金额',
        //   prop: 'amount',
        //   width: '160',
        //   align: 'center',
        //   tooltip: false
        // },
        {
          label: '所属组织',
          prop: 'organization',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '审核状态',
          prop: 'audit_status',
          width: '150',
          align: 'center',
          tooltip: false
        },
        {
          label: '审核原因',
          prop: 'audit_notes',
          width: '100',
          align: 'center',
          component: appText,
          propsHandler({ row }) {
            return { text: row.audit_notes }
          }
        },
        {
          label: '是否生成采购合同',
          prop: 'contract_status',
          width: '230',
          align: 'center',
          tooltip: false
        },
        {
          label: '合同编码',
          prop: 'contract_code',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '商品编码|商品名称|交货日期',
          prop: 'goods_code',
          width: '400',
          align: 'center',
          tooltip: true,
          component: appHtml,
          propsHandler({ row }) {
            const list = row.products.map((arr) => {
              if (arr.arrive_date) {
                arr.date = formatDate(arr.arrive_date, '{y}-{m}-{d}')
              } else {
                arr.date = '-'
              }
              return '<div>' + arr.goods_code + '|' + arr.goods_name + '|' + arr.date + '</div>'
            })
            const listString = list.join('<el-divider class="line_style"></el-divider>')
            return { text: listString }
          }
        },
        {
          label: '配件编码|配件名称|交货日期',
          prop: 'goods_code',
          width: '400',
          align: 'center',
          tooltip: true,
          component: appHtml,
          propsHandler({ row }) {
            const list = row.parts.map((arr) => {
              if (arr.arrive_date) {
                arr.date = formatDate(arr.arrive_date, '{y}-{m}-{d}')
              } else {
                arr.date = '-'
              }
              return '<div>' + arr.goods_code + '|' + arr.goods_name + '|' + arr.date + '</div>'
            })
            const listString = list.join('<el-divider class="line_style"></el-divider>')
            return { text: listString }
          }
        },
        {
          label: '创建人',
          prop: 'created_by_name',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建时间',
          prop: 'created_at',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改人',
          prop: 'updated_by_name',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改时间',
          prop: 'updated_at',
          width: '200',
          align: 'center',
          tooltip: false
        }
      ],
      /** *
       * 字典表组件
       */
      columnsSchema: {
        采购申请单编码: {
          propsHandler({ col, row }) {
            return {
              code: row[col.prop]
            }
          },
          component: codeItem,
          listeners: {
            click: codeClickHandler
          }
        },
        是否生成采购合同: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['cooperationStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        审核状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['auditStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        }
      },
      issignContract: [
        {
          name: '采购单编码',
          code: 'code'
        }
      ],
      form: {
        audit_status: null,
        audit_notes: null
      },
      sdioRadio: null, // 审核驳回
      sdioAdopt: null, // 审核通过
      bareData: [
        {
          suppierCode: '000',
          chineseName: '11',
          enName: '11',
          suppier: '11',
          rate: '11',
          number: '11',
          unitPrice: '11',
          purchaseAmount: '11',
          demandTime: '11',
          date: '11',
          tip: '11'
        }
      ],
      loadingBare: false,
      roleCodeRule: {
        audit_status: [
          { required: true, message: '请选择审核', trigger: 'blur' }
        ],
        audit_notes: [
          { required: true, message: '请输入审核意见', trigger: 'blur' },
          { max: 500, message: '审核意见必须在500个字符以内', trigger: 'blur' }
        ]
      },
      arriveDateRule: [
        {
          required: true,
          message: '请选择交货日期',
          trigger: ['change', 'blur']
        }
      ],
      numberRule: [
        { required: true, message: '请输入数量', trigger: ['change', 'blur'] }
      ],
      priceRule: [
        { required: true, message: '请输入价格', trigger: ['change', 'blur'] }
      ],
      infoLoading: false,
      exportLoading: false,
      cachePaths: [
        '/supplyChain/purchaseRequisition/add',
        '/supplyChain/purchaseContract/outWaybill/',
        '/supplyChain/purchaseContract/modifyContract',
        '/supplyChain/purchaseContract/contractDetails'
      ],
      //
      exportUrl: '/purchase-order/export',
      formVisibleDown: false,
      downLoadParams: {},
      optionsModul: [
        {
          key: 'id',
          label: 'ID'
        },
        {
          key: 'code',
          label: '采购申请单编码'
        },
        {
          key: 'amount',
          label: '采购总金额'
        },
        {
          key: 'audit_status_text',
          label: '审核状态'
        },
        {
          key: 'contract_status_text',
          label: '是否生成采购合同'
        },
        {
          key: 'contract_code',
          label: '合同编码'
        },
        {
          key: 'organization',
          label: '所属组织'
        },
        {
          key: 'goods_code',
          label: '商品编码'
        },
        {
          key: 'goods_name',
          label: '商品名称'
        },
        {
          key: 'arrive_date',
          label: '交付日期'
        },
        {
          key: 'organization',
          label: '所属组织'
        },
        {
          key: 'organization',
          label: '所属组织'
        },
        {
          key: 'created_by_name',
          label: '创建人'
        },
        {
          key: 'created_at',
          label: '创建时间'
        },
        {
          key: 'updated_by_name',
          label: '修改人'
        },
        {
          key: 'updated_at',
          label: '修改时间'
        }
      ]

    }
  },
  created() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js），第二个为参数
    this.query()
  },
  activated() {
    this.query()
  },
  methods: {
    beforeSearch() {
      const vm = this
      vm.searchParams.start_at_creat = ''
      vm.searchParams.end_at_creat = ''
      // 生成日期转化
      if (vm.searchParams.dateCreat && vm.searchParams.dateCreat.length > 0) {
        vm.searchParams.start_at_creat = vm.searchParams.dateCreat[0]
        vm.searchParams.end_at_creat = vm.searchParams.dateCreat[1]
      } else {
        vm.searchParams.start_at_creat = ''
        vm.searchParams.end_at_creat = ''
      }
    },
    changeMoney(value) {
      const arr = this.form.products
      this.form.amount = arr.reduce((total, currentValue, currentIndex, arr) => {
        arr.newPrice = accMul(currentValue['price'], currentValue['number'])
        arr.num = arr.newPrice ? total + arr.newPrice : total
        arr.numberTotal = Math.round(arr.num * 100) / 100
        return arr.numberTotal
      }, 0)
    },
    // 导出
    handleExport() {
      const vm = this
      vm.beforeSearch()
      const { audit_status, code, contract_code, start_at_creat, end_at_creat } = vm.searchParams
      // const code = vm.searchParams.value
      const params = { audit_status, code, contract_code, start_at_creat, end_at_creat }
      //   vm.handleExportxlsx(vm.exportUrl, params)
      vm.downLoadParams = params
      vm.formVisibleDown = true
    },
    // 导出
    // handleExport() {
    //   const vm = this
    //   vm.exportLoading = true
    //   const params = {
    //     export_filed: ''
    //   }
    //   vm.$http.post('/purchase-order/export', { params }).then(res => {
    //     downloadxlsx(res.data)
    //     vm.exportLoading = false
    //   }).catch(() => {
    //     vm.exportLoading = false
    //   })
    // },
    handleSearch() {
      const vm = this
      vm.searchParams.page = 1
      vm.query()
    },
    // 刷新
    handleRefresh() {
      // this.searchParams.type = ''
      this.searchParams.dateCreat = []
      this.searchParams.code = ''
      this.searchParams.audit_status = ''
      this.searchParams.contract_code = ''
      this.searchParams.start_at_creat = ''
      this.searchParams.end_at_creat = ''
      this.searchParams.page = 1
      this.searchParams.limit = 10
      this.query()
    },
    // 提交审核
    submitReview() {
      const dataLength = this.checkedList.length
      if (dataLength === 0) {
        this.$message.error('最少选择一条数据')
        return false
      }
      const isAudit = this.checkedList.findIndex((v) => ![0, -1, -2].includes(v.audit_status))
      if (isAudit !== -1) {
        this.$message.error('数据已提交审核，请重新选择')
        return false
      }
      this.$confirm(`确定提交审核吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .post(`/purchase-order/submit-audit`, { ids: this.ids })
          .then((res) => {
            if (res.code === 10000) {
              this.$message.success('提交审核成功')
              this.query()
            }
          })
          .catch(() => {
            this.loading = false
          })
      })
    },
    // 采购员审核、运营审核
    bulkShipment(adopt, reject) {
      const that = this
      const dataLength = that.checkedList.length
      that.isInfo = false
      if (dataLength === 0) {
        that.$message.error('最少选择一条数据')
        return false
      }
      if (dataLength > 1) {
        that.$message.error('最多选择一条数据')
        return false
      }
      // 采购员
      if (adopt === 2 && that.checkedList[0].audit_status !== 1) {
        that.$message.error('请选择待采购员审核的数据')
        return false
      }
      // 运营
      if (adopt === 3 && that.checkedList[0].audit_status !== 2) {
        that.$message.error('请选择待运营审核的数据')
        return false
      }
      that.sdioRadio = reject
      that.sdioAdopt = adopt
      that.form.audit_status = adopt
      that.form.audit_notes = ''
      that.dialogAddVisible = true
      that.getSupplierList(this.checkedList[0].id)
    },
    getSupplierList(id) {
      this.infoLoading = true
      this.$http
        .get(`/purchase-order/${id}`)
        .then((res) => {
          if (res.code === 10000) {
            const { audit_status, audit_notes } = this.form
            this.form = {}
            this.form = Object.assign(res.data, this.form)
            this.form.products = this.form.products.map((e) => {
              e['old_number'] = e.number
              return e
            })
            this.form.parts = this.form.parts.map((e) => {
              e['old_number'] = e.number
              return e
            })
            this.form.audit_status = audit_status
            this.form.audit_notes = audit_notes
          }
          this.infoLoading = false
        })
        .catch(() => {
          this.infoLoading = false
        })
    },
    // 采购审核
    saveData() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const productArray = this.form.products
            .concat(this.form.parts)
            .map((item) => {
              return {
                id: item.id,
                number: item.number,
                arrive_date: item.arrive_date,
                price: item.price || 0
              }
            })
          const param = {
            id: this.form.id,
            audit_status: this.form.audit_status,
            audit_notes: this.form.audit_notes,
            products: productArray
          }
          const { audit_status } = this.form
          let url = ''
          if ([2, -1].includes(audit_status)) {
            url = '/purchase-order/change-audit-status'
          } else {
            url = '/purchase-order/operate-change-audit-status'
          }
          this.$http
            .post(url, param)
            .then((res) => {
              if (res.code === 10000) {
                this.$message.success('审核成功')
                this.query()
              }
            })
            .catch(() => {
              this.loading = false
            })
          this.dialogAddVisible = false
        }
      })
    },
    // 自定义操作栏
    columnsHandler(cols) {
      const that = this
      return cols.concat({
        width: '135',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({ row }) {
          const isShow = [0, 1, -1, -2].includes(row.audit_status)
          return {
            row,
            del: isShow,
            edit: isShow,
            delAction: 'purchaseOrder@delete',
            editAction: 'purchaseOrder@update'
          }
        },
        component: operationBtnGroup,
        listeners: {
          deleteTableClick(row) {
            that
              .$confirm('您确定要删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
              .then(() => {
                that.loading = true
                // 点击确定
                that.$http
                  .delete(`/purchase-order/${row.id}`)
                  .then((res) => {
                    that.loading = false
                    if (res.code === 10000) {
                      that.$message.success('删除成功')
                      that.query()
                    }
                  })
                  .catch(() => {
                    that.loading = false
                  })
              })
              .catch(() => {
                that.loading = false
              })
          },
          editTableClick(row) {
            that.$router.push({
              path: '/supplyChain/purchaseRequisition/add',
              query: { title: '编辑申请采购单', id: row.id }
            })
          }
        }
      })
    },
    // 批量删除
    batchDeleteData() {
      if (!this.ids.length) {
        this.$message.error('至少选择一行数据')
        return
      } else {
        this.$confirm('您确定要删除, 是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          // 点击确定
        })
          .then(() => {
            this.$http
              .post('purchase-order/batch-delete', { ids: this.ids })
              .then((res) => {
                this.loading = false
                if (res) {
                  this.$message.success('删除成功')
                  this.query()
                }
              })
          })
          .catch(() => {
            // 点击取消
            this.$message.success({
              type: 'info',
              message: '已取消删除'
            })
          })
      }
    },
    // 新增申请单
    addPurchaseClick() {
      this.$router.push('/supplyChain/purchaseRequisition/add')
    },
    // 转为采购合同
    transferPurchase() {
      const dataLength = this.checkedList.length
      if (dataLength === 0) {
        this.$message.error('最少选择一条数据')
        return false
      }
      if (dataLength > 1) {
        this.$message.error('最多选择一条数据')
        return false
      }
      const first = this.checkedList[0]
      if (first.contract_status !== 0 || first.audit_status !== 3) {
        this.$message.error('请选择运营审核通过且未生成合同数据')
        return false
      }
      this.$refs.coverContract.show(this.ids[0])
      // this.$confirm(`确定转为采购合同？`, '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   this.$http
      //     .post(`/purchase-contract`, { id: this.ids[0] })
      //     .then((res) => {
      //       if (res.code === 10000) {
      //         this.$message.success('转为采购合同成功')
      //         this.query()
      //       }
      //     })
      //     .catch(() => {
      //       this.loading = false
      //     })
      // })
    },
    handleSizeChange(val) {
      this.searchParams.limit = val
      this.query()
    },
    handleCurrentChange(val) {
      this.searchParams.page = val
      this.query()
    },
    query() {
      this.beforeSearch()
      let url = '/purchase-order'
      const { page, limit, code, audit_status, contract_code, end_at_creat, start_at_creat } = this.searchParams
      url += `?page=${page}&limit=${limit}&audit_status=${audit_status}`
      if (code) {
        url += `&code=${code}`
      }
      if (contract_code) {
        url += `&contract_code=${contract_code}`
      }
      console.log(end_at_creat, start_at_creat)
      if (end_at_creat || start_at_creat) {
        url += `&end_at_creat=${end_at_creat}&start_at_creat=${start_at_creat}`
      }
      this.initTableData(url)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
